using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using UnityEngine;
using Debug = UnityEngine.Debug;

/// <summary>
/// 玩家数据类，管理玩家所有状态和数据
/// </summary>
public class PlayerData : MonoBehaviour, ITarget
{
    private EffectSystem effectSystem;

    [Header("基础属性")]
    [SerializeField] private int _currentHP = 80;
    [SerializeField] private int _maxHP = 80;

    // ITarget 接口实现
    public int currentHP
    {
        get => _currentHP;
        set => _currentHP = Mathf.Clamp(value, 0, maxHP);
    }

    public int maxHP => _maxHP;
    public int Block { get; set; } = 0;

    [Header("玩家特有属性")]
    [SerializeField] private int _energy = 3;
    [SerializeField] private int _maxEnergy = 3;

    public int energy
    {
        get => _energy;
        set => _energy = Mathf.Max(0, value);
    }
    
    public int maxEnergy => _maxEnergy;

    [Header("Buff管理")]
    private List<Buff> buffs = new List<Buff>();

    [Header("游戏进度")]
    public int gold = 0;           // 学力
    public int credit = 0;         // 学分
    public List<string> relics = new List<string>(); // 遗物列表
    public List<string> potions = new List<string>(); // 药水列表

    // 事件
    public System.Action<int> OnHPChanged;
    public System.Action<int> OnEnergyChanged;
    public System.Action<int> OnGoldChanged;
    public System.Action<int> OnCreditChanged;

    private void Awake()
    {
        effectSystem = FindObjectOfType<EffectSystem>();
        if (effectSystem == null)
        {
            Debug.LogError("EffectSystem not found in scene!");
        }
        Debug.Log($"[PlayerData] 初始化完成 - HP: {currentHP}/{maxHP}, 能量: {energy}/{maxEnergy}");
    }
    /*private void Start()
    {
        effectSystem = FindObjectOfType<EffectSystem>();
        if (effectSystem == null)
        {
            Debug.LogError("EffectSystem not found in scene!");
        }
        Debug.Log($"[PlayerData] 初始化完成 - HP: {currentHP}/{maxHP}, 能量: {energy}/{maxEnergy}");
    }*/
    // ITarget 接口实现
    public void AddBuff(Buff buff)
    {
        Buff existingBuff = GetBuff(buff.type);
        if (existingBuff != null)
        {
            existingBuff.stacks += buff.stacks;
        }
        else
        {
            buffs.Add(buff);
        }

        Debug.Log($"[Player] 获得 Buff: {buff.type} x{buff.stacks}");
    }

    public Buff GetBuff(BuffType type)
    {
        return buffs.FirstOrDefault(b => b.type == type);
    }
    // 1. 获取所有 Buff (供 EffectSystem 遍历)
    public List<Buff> GetAllBuffs()
    {
        return buffs;
    }
    // 2. 清理过期 Buff (供 EffectSystem 调用，封装了清理逻辑)
    public void RemoveExpiredBuffs()
    {
        // 找出所有层数 <= 0 的 Buff
        List<Buff> expiredBuffs = buffs.Where(b => b.stacks <= 0).ToList();
        
        // 移除它们
        foreach (var buff in expiredBuffs)
        {
            buffs.Remove(buff);
            Debug.Log($"[Player] 移除过期 Buff: {buff.type}");
        }
    }

    public bool IsAlive()
    {
        return currentHP > 0;
    }

    // 玩家特有方法
    public bool CanUseCard(int cardEnergyCost)
    {
        return energy >= cardEnergyCost;
    }

    public void UseEnergy(int amount)
    {
        energy = Mathf.Max(0, energy - amount);
        OnEnergyChanged?.Invoke(energy);
        Debug.Log($"消耗 {amount} 点能量，剩余能量: {energy}");
    }

    public void StartTurn()
    {
        // 每回合开始时重置能量
        energy = maxEnergy;
        OnEnergyChanged?.Invoke(energy);
        Debug.Log($"回合开始，能量重置为: {energy}");
        // 清除格挡
        // 确保清除格挡 (player.Block = 0;) 发生在 进入玩家回合之前，而不是在 PlayerData.StartTurn()
        // Block = 0;
        // 处理回合开始时的Buff效果
        ProcessStartTurnBuffs();
    }

    public void EndTurn()
    {
        // 处理回合结束时的Buff效果
        effectSystem.TriggerAtTurnEnd(this);

        Debug.Log($"回合结束，剩余能量: {energy}");
    }

    // 资源管理
    public void AddGold(int amount)
    {
        gold += amount;
        OnGoldChanged?.Invoke(gold);
        Debug.Log($"获得 {amount} 学力，当前学力: {gold}");
    }

    public void AddCredit(int amount)
    {
        credit += amount;
        OnCreditChanged?.Invoke(credit);
        Debug.Log($"获得 {amount} 学分，当前学分: {credit}");
    }

    public bool SpendGold(int amount)
    {
        if (gold >= amount)
        {
            gold -= amount;
            OnGoldChanged?.Invoke(gold);
            Debug.Log($"消耗 {amount} 学力，剩余学力: {gold}");
            return true;
        }
        return false;
    }

    // 治疗和恢复
    public void Heal(int amount)
    {
        int oldHP = currentHP;
        currentHP += amount;
        OnHPChanged?.Invoke(currentHP);
        Debug.Log($"玩家恢复 {amount} 点生命值，当前生命值: {currentHP}/{maxHP}");
    }

    public void IncreaseMaxHP(int amount)
    {
        _maxHP += amount;
        currentHP += amount;
        OnHPChanged?.Invoke(currentHP);
        Debug.Log($"玩家最大生命值增加 {amount}，当前: {maxHP}");
    }

    // Buff处理
    private void ProcessStartTurnBuffs()
    {
        effectSystem.TriggerAtTurnStart(this);
    }

    // 遗物管理
    public void AddRelic(string relicId)
    {
        if (!relics.Contains(relicId))
        {
            relics.Add(relicId);
            Debug.Log($"获得遗物: {relicId}");
        }
    }

    public bool HasRelic(string relicId)
    {
        return relics.Contains(relicId);
    }

    // 重置状态
    public void ResetForCombat()
    {
        Block = 0;
        buffs.Clear();
        energy = maxEnergy;
        OnEnergyChanged?.Invoke(energy);
        Debug.Log("玩家战斗状态已重置");
    }

    // 调试方法
    public void DisplayState()
    {
        Debug.Log($"--- 玩家状态 ---");
        Debug.Log($"HP: {currentHP}/{maxHP} | Block: {Block} | Energy: {energy}/{maxEnergy}");
        Debug.Log($"学力: {gold} | 学分: {credit}");
        Debug.Log($"遗物: {string.Join(", ", relics)}");
        Debug.Log($"Buffs: {string.Join(", ", buffs.Select(b => $"{b.type}x{b.stacks}"))}");
        Debug.Log("----------------");
    }

    //深度复制
    public void DeepCopyTo(PlayerData target)
    {
        if (target == null)
        {
            Debug.LogError("复制目标不能为 null");
            return;
        }

        try
        {
            // 基础属性
            target._currentHP = this._currentHP;
            target._maxHP = this._maxHP;
            target.Block = this.Block;

            // 能量
            target._energy = this._energy;
            target._maxEnergy = this._maxEnergy;

            // 游戏进度
            target.gold = this.gold;
            target.credit = this.credit;
            target.relics = new List<string>(this.relics);
            target.potions = new List<string>(this.potions);

            Debug.Log($"[PlayerData] 深度复制完成: {this.gameObject.name} -> {target.gameObject.name}");
        }
        catch (System.Exception e)
        {
            Debug.LogError($"[PlayerData] 复制过程中发生错误: {e.Message}");
        }
    }
}